package top.lcpsky.flashcards.web;

import static com.google.common.collect.Lists.newArrayList;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import top.lcpsky.flashcards.dto.CardDto;
import top.lcpsky.flashcards.entity.CardsWithBLOBs;
import top.lcpsky.flashcards.entity.Todo;
import top.lcpsky.flashcards.service.CardsService;
import top.lcpsky.flashcards.service.TodoService;


/**   
 * @ClassName:  ViewController   
 * @author: lcp
 * @date:   2020年5月9日 下午7:06:24   
 *     
 * @Copyright: 2020 www.ankept.com Inc. All rights reserved. 
 */
@Controller
public class RouterController {
	@Autowired
	private CardsService cardsSvc;
	@Autowired
	private TodoService todoService;
	
    @GetMapping(value = "/")
    public String forwardToLogin(HttpSession session,Model model){
    	setLoginStatusToModel(session, model);
        return "forward:login";
    }
	/**   
	 * @Title: setLoginStatusToModel   
	 * @param: @param session
	 * @param: @param model      
	 * @return: void      
	 * @throws   
	 */
	public static void setLoginStatusToModel(HttpSession session, Model model) {
		Boolean loginStatus;
		if (session!=null &&(loginStatus = (Boolean) session.getAttribute("loginStatus"))!=null && loginStatus == true) {
			model.addAttribute("loginStatus",true);
		}else {
			model.addAttribute("loginStatus",null);
		}
	}
	public static Boolean getLoginStatus(HttpSession session) {
		Boolean loginStatus;
		if (session!=null &&(loginStatus = (Boolean) session.getAttribute("loginStatus"))!=null && loginStatus == true) {
			loginStatus = true;
		}else {
			loginStatus = null;
		}
		return loginStatus;
	}
    @GetMapping(value = "login")
    public String toLoginPage(HttpSession session,Model model){
    	setLoginStatusToModel(session, model);
        return "login";
    }
    @GetMapping(value = "index")
    public String toIndexPage(){
    	return "index";
    }
    @GetMapping(value = "filemgr")
    public String toFilemgrPage(HttpSession session,Model model){
		if (getLoginStatus(session)==null) {
	        return "redirect:/login";
		}
    	return "filemanager";
	}
    @GetMapping(value = "todolist")
    public String toToDoListPage(HttpSession session,Model model){
    	if (getLoginStatus(session)==null) {
    		return "redirect:/login";
		}
		List<Todo> todos = todoService.getAllTodos();
		model.addAttribute("todos", todos);
    	return "todo";
    }
    @GetMapping(value = "navtool")
    public String toToNavigatePage(HttpSession session,Model model){
    	if (getLoginStatus(session)==null) {
    		return "redirect:/login";
    	}
    	return "navmgr";
    }
    @GetMapping(value = "stockq")
    public String toToStockPage(HttpSession session,Model model){
    	if (getLoginStatus(session)==null) {
    		return "redirect:/login";
    	}
    	return "stockmgr";
    }
	
    @GetMapping(value = "cards")
    public String toCardPage(HttpSession session,Model model){
	    if (getLoginStatus(session)==null) {
	        return "redirect:/login";
		}
		List<CardsWithBLOBs> allCards = cardsSvc.findAll(null);
		session.setAttribute("cards", allCards);
	    return "cards";
    }
    @GetMapping(value = "filter_cards/{cardType}")
    public String toCardPageAndFilterCards(HttpSession session,@PathVariable("cardType") String cardType,Model model){
    	if (getLoginStatus(session)==null) {
    		return "redirect:/login";
    	}
    	Byte type = null;
    	switch (cardType) {
		case "general":
			type = 1;
			break;
		case "code":
			type = 2;
			break;
		default:
			break;
		} 
    	List<CardsWithBLOBs> allCards = newArrayList();
    	if (cardType.contains("known")) {
    		allCards = cardsSvc.findAllByKnown((byte) (cardType.equals("known")?1:0));
		}else {
			allCards = cardsSvc.findAll(type);
		}
    	session.setAttribute("filter_name", cardType);
    	session.setAttribute("cards", allCards);
    	return "cards";
    }
 
    @GetMapping(value = "delete/{id}")
    public String deleteCard(HttpSession session,@PathVariable(name = "id") String id,Model model){
    	if (getLoginStatus(session)==null) {
    		return "redirect:login";
    	}
    	cardsSvc.deleteCardById(Integer.valueOf(id.replace(",","")));
    	return "redirect:/cards";
    }
    @PostMapping(value = "edit_card")
    public String editCard(HttpSession session,CardDto card,Model model){
    	if (getLoginStatus(session)==null) {
    		return "redirect:login";
		}
    	CardsWithBLOBs cardModel = new CardsWithBLOBs(card);
		cardsSvc.updateCard(cardModel);
    	return "redirect:/cards";
    }
    @GetMapping(value = "memorize")
    public String toMemorizePage(HttpSession session,Model model){
    	return "memorize";
    }
    @GetMapping(value = "edit")
    public String toEditPage(HttpSession session,Model model){
    	return "edit";
    }
    @GetMapping(value = {"general","general/{id}"})
    public String toGeneralPage(HttpSession session,@PathVariable(name="id",required = false)String id,Model model){
    	 if (getLoginStatus(session)==null) {
    		  return "redirect:login";
  	    }
		CardsWithBLOBs card = null;
		if(StringUtils.isEmpty(id)){
			card = memorize("general", null);
		}else{
			card = memorize("general", Integer.valueOf(id.replaceAll(",", "")));
			cardsSvc.updateCardUnknown(Integer.valueOf(id.replaceAll(",", "")));
			model.addAttribute("get_flashed_messages", 0);
		}
    	model.addAttribute("card", card );
    	model.addAttribute("card_type", "general");
    	if(card.getBack().length()<75) {
    		model.addAttribute("short_answer", 1);
    	}else {
    		model.addAttribute("short_answer", 0);
		}
    	return "memorize";
    }
    /**   
	 * @Title: memorize   
	 * @param: @param string
	 * @param: @param object
	 * @param: @return      
	 * @return: Cards      
	 * @throws   
	 */
	private CardsWithBLOBs memorize(String cardType, Integer cardId) {
		CardsWithBLOBs card;
		int type = 0;
		if("general".equals(cardType)) {
			type = 1;
		}else if("code".equals(cardType)) {
			type = 2;
		}else {
			card = null;
		}
		if (cardId != null) {
			card = cardsSvc.findCardById(cardId);
		}else {
			card = cardsSvc.findCardByType(type);
		}
		return card;
	}
	@GetMapping(value = {"code","code/{id}"})
    public String toCodePage(HttpSession session,@PathVariable(name="id",required = false)String id,Model model){
		if (getLoginStatus(session)==null) {
   		  return "redirect:login";
		}
		CardsWithBLOBs card = null;
		if(StringUtils.isEmpty(id)){
			card = memorize("code", null);
		}else{
			card = memorize("code", Integer.valueOf(id.replaceAll(",", "")));
			cardsSvc.updateCardUnknown(Integer.valueOf(id.replaceAll(",", "")));
			model.addAttribute("get_flashed_messages", 0);
		}
		model.addAttribute("card_type", "code");
    	model.addAttribute("card", card );
    	return "memorize";
	}
	
	@GetMapping(value = "mark_known/{id}/{cardType}")
    public String markKnown(HttpSession session,@PathVariable(name="id")String id,@PathVariable(name="cardType")String cardType,Model model){
		if (getLoginStatus(session)==null) {
   		  return "redirect:login";
		}
		cardsSvc.updateCardKnown(Integer.valueOf(id.replaceAll(",", "")));
		CardsWithBLOBs card = memorize(cardType, Integer.valueOf(id.replaceAll(",", "")));
		model.addAttribute("card_type", cardType);
		model.addAttribute("card", card );
		if(card.getBack().length()<75) {
    		model.addAttribute("short_answer", 1);
    	}else {
    		model.addAttribute("short_answer", 0);
		}
		model.addAttribute("get_flashed_messages", 1);
    	return "memorize";
    }
}